package com.cal.utms.dao.maintenance;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.cal.utms.entity.FundInstrumentMap;
import com.cal.utms.entity.InstrumentType;
import com.cal.utms.util.HibernateUtil;

public class FundInstrumentMapDao {
	
	public Object add(FundInstrumentMap fim) {
		Object obj;
		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		System.out.println("Saving Fund Instrument Map ");
		try {
			tx = session.beginTransaction();
			obj = session.save(fim);
			tx.commit();
			System.out.println("Fund Instrument Map saved");
		} catch (Exception ex) {
			tx.rollback();
			obj = new Object();
			System.out.println("Exception in saving Fund Instrument Map "
					+ ex.getMessage());
			ex.printStackTrace();
		} finally {
			session.close();
		}
		return obj;
	}
	
	public void delete(FundInstrumentMap fim) {
		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		//System.out.println("Deleting Custodian Contact Person "+ccp.getName());
		try {
			tx = session.beginTransaction();
			session.delete(fim);
			tx.commit();
			//System.out.println("Custodian Contact Person ");
		} catch (Exception ex) {
			tx.rollback();
			//System.out.println("Exception in saving Custodian Contact Person "+ ex.getMessage());
			ex.printStackTrace();
		} finally {
			session.close();
		}

	}
	
	@SuppressWarnings("unchecked")
	public List<InstrumentType> getInsType(int fundId, String dealCode){
		List<InstrumentType> insTypeList = new ArrayList<InstrumentType>();
		InstrumentType instrumentType = null;		
		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Query query = session.createQuery("select c.instrumentTypeId from FundInstrumentMap c where c.dealTypeBean.code = :dealCode and c.fund.id= :fundId");
			query.setParameter("dealCode", dealCode);
			query.setParameter("fundId", fundId);
			List<Integer> idList= query.list();
			for(Integer i:idList){
				instrumentType = (InstrumentType) session.get(InstrumentType.class, i);
				insTypeList.add(instrumentType);
			}
			tx.commit();		
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			System.out.println("Exception getInsType in FundInsMap :"+ e.getMessage());
			e.printStackTrace();
		} finally {
			session.close();
		}
		
		return insTypeList;
	}
	
	public static void main(String[] args) {
		FundInstrumentMapDao fdao = new FundInstrumentMapDao();
		for(InstrumentType insType: fdao.getInsType(18, "PURCH")){
			System.out.println(insType.getInstrumentName());
		};
		
	}

}
